package com.ruoyi.web.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.ruoyi.dto.reqDto.imagePreviewReqDto;
import com.ruoyi.entity.FileDataEntity;
import com.ruoyi.entity.FileEntity;
import com.ruoyi.entity.originImageEntity;
import com.ruoyi.mapper.FileMapper;
import com.ruoyi.entity.originVideoEntity;
import com.ruoyi.utils.dateUtils;
import com.ruoyi.web.service.FileService;
import com.ruoyi.web.service.OssService;
import lombok.Cleanup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.exception.file.FileNameExistsException;
import static com.ruoyi.utils.serializaUtil.Str2List;
import java.util.UUID;

/**
 * @author Chen Lin
 * @date 2022.03.23  10:32 AM
 * @description
 */
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, originVideoEntity> implements FileService {
    //分割符号
    public static String segSymbols = "#";

    @Value("${minio.origin-bucket}")
    private String originBucket;

    @Value("${minio.bucket}")
    private String pneumaticBucket;

    @Autowired
    private OssService ossService;

    @Override
    public Integer saveImageBatchService(MultipartFile[] files, String taskId, BigInteger timeStamp) throws IOException {
        //当前日期文件夹
        String dateDirectoy= dateUtils.getCurrentDate();
        //存储文件名字符串
        StringBuffer stringBuffer = new StringBuffer();
        for(MultipartFile file: files){
            String imageName=file.getOriginalFilename();
            try {
                @Cleanup
                InputStream inputStream = file.getInputStream();
                String fileName ="/"+dateDirectoy+"/"+imageName;
                ossService.putObject(originBucket,fileName,inputStream);
            }catch(Exception e){

            }
            if (stringBuffer.length() == 0) {
                stringBuffer.append(imageName);
            } else {
                stringBuffer.append(segSymbols + imageName);
            }
        }
        originImageEntity et=new originImageEntity();
        et.setTaskCode("sssss");
        et.setImagesNameCompose(stringBuffer.toString());
        et.setDirectory("/"+dateDirectoy);
        et.setCreateUser("ss122");
        et.setCreateTime("sssss");
        et.setTaskId(taskId);
        et.setTimeStamp(timeStamp);
        Integer res=baseMapper.saveBatchImage(et);
        return null;
    }

    /**
     * 根据任务ID和当前分页index获取所有图片外链地址信息
     * @param taskId
     * @param index
     * @return
     */

    @Override
    public imagePreviewReqDto getImagesUrlInfo(String taskId, Integer index) {
        //返回给前端的数据
        imagePreviewReqDto req=new imagePreviewReqDto();
        //存放图片外链地址list
        List<String> ImageList=new ArrayList<>();
        //从数据库获取该任务下的所有图片信息
        List<originImageEntity> imagesUrlsInfo=baseMapper.getImageBatchInfo(taskId);
        //获取分页的页码数
        Integer pages=imagesUrlsInfo.size();
        //获取当前分页
        originImageEntity imageUrl= imagesUrlsInfo.get(index);
        String imagesName=imageUrl.getImagesNameCompose();
        String directory=imageUrl.getDirectory();
        //对图片名进行分解获取list
//        List<String> urlList=Str2List(imagesName,String.class);
        String[] urlList = imagesName.split("#");
        for(String ig:urlList){
            String file=directory+"/"+ig;
            String URL=ossService.getObjectUrl(originBucket,file,2);
            ImageList.add(URL);
        }
        req.setPages(pages);
        req.setImageUrlList(ImageList);
        return req;
    }

    @Override
    public List<originVideoEntity> getVideoList(String taskId) {
        List<originVideoEntity> vedioList=baseMapper.getVedioList(taskId);
        return vedioList;
    }

    @Override
    public String getVideoUrl(String directory,String fileName) {
        String file=directory+"/"+fileName;
        String URL=ossService.getObjectUrl(originBucket,file,2);
        return URL;
    }


    @Override
    public List<String> getDownloadImageUrl(String taskId) {
        //存放图片外链地址list
        List<String> ImageList=new ArrayList<>();
        //从数据库获取该任务下的所有图片信息
        List<originImageEntity> imagesUrlsInfo=baseMapper.getImageBatchInfo(taskId);
        for(originImageEntity imageUrl : imagesUrlsInfo){
            String imagesName=imageUrl.getImagesNameCompose();
            String directory=imageUrl.getDirectory();
            //对图片名进行分解获取list
            String[] urlList = imagesName.split("#");
            for(String ig:urlList){
                String file=directory+"/"+ig;
                String URL=ossService.getObjectUrl(originBucket,file,2);
                ImageList.add(URL);
            }

        }
        return ImageList;
    }

    @Override
    public Integer deleteImage(String taskId, String imageName) {
        List<originImageEntity> imagesUrlsInfo=baseMapper.getImageBatchInfo(taskId);
        for(originImageEntity imageUrl : imagesUrlsInfo){
            String imagesName=imageUrl.getImagesNameCompose();
            Integer id=imageUrl.getId();
            String directory=imageUrl.getDirectory();
            String objectName = directory + "/" + imageName;
            //根据图片名称删除minio图片
            ossService.removeObject(originBucket, objectName);
            //判断图片整体拼接名称是否包含图片名称
            if(imagesName.equals(imageName)){
                Integer res = baseMapper.deleteImage(id);
                //找到就跳出
                break;
            }
            else {
                if (imagesName.contains(imageName)) {
                    //检索到具体分隔符逻辑
                    String spliteTag = "#" + imageName + "#";
                    if (!imagesName.contains(spliteTag)) {
                        spliteTag = "#" + imageName;
                        if (!imagesName.contains(spliteTag)) {
                            spliteTag = imageName + "#";
                            if (!imagesName.contains(spliteTag)) {
                                spliteTag = imageName;
                            }
                        }
                    }
                    String[] images = imagesName.split(spliteTag);
                    String newImageName = "";
                    if (spliteTag.equals("#" + imageName)) {
                        newImageName = images[0];
                    } else if (spliteTag.equals(imageName + "#")) {
                        newImageName = images[1];
                    } else {
                        for (String name : images) {
                            if(newImageName.length()==0){
                                newImageName=name.trim();
                            }
                            else{
                                newImageName = (newImageName + "#" + name).trim();
                            }
                        }

                    }
                    Integer res = baseMapper.updateImage(newImageName, id);
                    //找到就跳出
                    break;
                }
            }

        }
        return null;
    }

    @Transactional
    public int savePneumaticFileService(MultipartFile[] files, String id, String workType, String fileType, Integer projectId, BigInteger timeStamp, List<FileDataEntity> fileData, List<FileDataEntity> resultData) throws IOException {
        //当前日期文件夹
        String dateDirectoy= dateUtils.getCurrentDate();
        //存储文件名字符串
        StringBuffer stringBuffer = new StringBuffer();
        for(MultipartFile file: files){
            String imageName=file.getOriginalFilename();
            try {
                @Cleanup
                InputStream inputStream = file.getInputStream();
                String fileName ="/"+workType+"/"+imageName;
                // 检查文件是否已存在
                if (ossService.isFileExist(pneumaticBucket, fileName)) {
                    throw new FileNameExistsException("File with name " + fileName + " already exists.");
                }
                ossService.putObject(pneumaticBucket, fileName,inputStream);
                FileEntity et = new FileEntity();
                et.setFileType(fileType);
                et.setProjectId(projectId);
                et.setCreateTime(timeStamp);
                et.setWorkType(workType);
                et.setFileName(imageName);
                et.setId(id);
                baseMapper.savePneumaticFile(et);
                if (fileType.equals("xlsx") || fileType.equals("xls") || fileType.equals("xlsm") || fileType.equals("txt") ) {
                    for (FileDataEntity fileItem: fileData) {
                        fileItem.setWorkType(workType);
                        baseMapper.saveFileData(fileItem);
                    }
                }
                if (fileType.equals("dat")) {
                    for (FileDataEntity fileItem: fileData) {
                        fileItem.setWorkType(workType);
                        baseMapper.saveFileData(fileItem);
                    }
                    if (resultData != null && !resultData.isEmpty()) {
                        for (FileDataEntity fileItem: resultData) {
                            fileItem.setWorkType(workType);
                            baseMapper.saveFileResultData(fileItem);
                        }
                    }
                }
                return 1;
            }catch(Exception e){
                System.out.println(e);
            }
            /*if (stringBuffer.length() == 0) {
                stringBuffer.append(imageName);
            } else {
                stringBuffer.append(segSymbols + imageName);
            }*/
        }

//        et.setTaskCode("sssss");
//        et.setImagesNameCompose(stringBuffer.toString());
//        et.setDirectory("/"+dateDirectoy);
//        et.setCreateUser("ss122");
//        et.setCreateTime("sssss");
//        et.setTaskId(taskId);
//        et.setTimeStamp(timeStamp);
//        Integer res=baseMapper.saveBatchImage(et);
        return 0;
    }
}
